from typing import Set
import dearpygui.dearpygui as dpg


class PopupList:
    def __init__(
        self,
        items: Set = set(),
        tag=0,
        label="name",
        persist: Set = set(),
        callback=None,
        user_data=None,
    ):
        self.items = items
        self.label = label
        self.persist = persist
        self.callback = callback
        self.user_data = user_data
        with dpg.popup(dpg.last_item(), dpg.mvMouseButton_Left, True, tag=tag) as win:
            self.tag = win
            with dpg.group(horizontal=True):
                dpg.add_text("新增：")
                dpg.add_input_text(tag=f"{win}_input")
                dpg.add_button(label="添加", callback=self.add)
            dpg.add_table(
                tag=f"{win}_table",
                row_background=True,
                borders_outerH=True,
                borders_outerV=True,
                borders_innerH=True,
                borders_innerV=True,
            )
            self.update_table()

    def update_table(self):
        name = f"{self.tag}_table"
        dpg.delete_item(name, children_only=True)
        dpg.add_table_column(parent=name, label=self.label)
        dpg.add_table_column(parent=name, label="操作", width_fixed=True)
        for item in self.items:
            if item in self.persist:
                continue
            with dpg.table_row(parent=name):
                dpg.add_text(item)
                dpg.add_button(label="删除", callback=self.delete, user_data=item)
        for item in self.persist:
            with dpg.table_row(parent=name):
                dpg.add_text(item)

    def show(self):
        dpg.show_item(self.tag)
        self.update_table()

    def add(self):
        input_name = f"{self.tag}_input"
        val = dpg.get_value(input_name).strip()
        dpg.set_value(input_name, "")
        if val == "" or val in self.items:
            return
        self.items.add(val)
        self.update_table()
        if self.callback is not None:
            self.callback()

    def delete(self, sender, app_data, user_data):
        self.items.remove(user_data)
        self.update_table()
        if self.callback is not None:
            self.callback()
